package hongxuda.api.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
泓旭达平台 0.0.1

*/
public class HttpClientUtil {
	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

	/**
	 * HttpClient的Get方法
	 * 
	 * @param url
	 * @param paramsMap
	 * @param charset
	 *            :编号格式
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public static String httpClientGet(String url, Map<String, String> paramsMap, String charset)
			throws HttpException, IOException {
		HttpClient client = new DefaultHttpClient();
		String json = null;
		HttpGet httpGet = new HttpGet();
		// 设置参数
		try {
			StringBuffer initStr = new StringBuffer();
			for (String param : paramsMap.keySet()) {
				initStr.append(initStr.length() > 0 ? "&" : "?");
				initStr.append(param).append("=")
						.append(paramsMap.get(param) != null ? URLEncoder.encode(paramsMap.get(param), charset) : "");
			}
			url += initStr.length() > 0 ? initStr.toString() : StringUtil.initString();
			httpGet.setURI(new URI(url != null ? url : StringUtil.initString()));
			System.out.println(url);
			log.info("httpClientGet.Url: {}", url != null ? url : StringUtil.initString());
		} catch (URISyntaxException e) {
			throw new HttpException("请求url格式错误。" + e.getMessage());
		}
		// 发送请求
		HttpResponse httpResponse = client.execute(httpGet);
		// 获取返回的数据
		HttpEntity entity = httpResponse.getEntity();
		byte[] body = EntityUtils.toByteArray(entity);
		StatusLine sL = httpResponse.getStatusLine();
		int statusCode = sL.getStatusCode();
		if (statusCode == 200) {
			if (StringUtil.isNullOrEmpty(charset)) {
				charset = "utf-8";
			}
			json = new String(body, charset);
			entity.consumeContent();
		} else {
			throw new HttpException("statusCode=" + statusCode);
		}
		return json;
	}

}
